//
//  ChangeUserName.m
//  DataStatistics
//
//  Created by oilklenze on 16/1/15.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "ChangeUserName.h"
#import "InformationViewController.h"
#import "ChangeUserNameModel.h"
#import "ChangeUserNameViewModel.h"


@interface ChangeUserName () <UITextFieldDelegate>

@property (strong, nonatomic) IBOutlet UITextField* userName;

@end

@implementation ChangeUserName

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.userName.text = USERNAME;
    self.userName.delegate = self;
    
    [self.userName endEditing:YES];
    UIButton* clearButton = [self.userName valueForKey:@"_clearButton"];
    [clearButton setImage:[UIImage imageNamed:@"关闭按钮"] forState:UIControlStateNormal];
    [clearButton setImage:[UIImage imageNamed:@"关闭按钮-on"] forState:UIControlStateHighlighted];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    [self.userName becomeFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)textFieldShouldReturn:(UITextField*)textField
{

    [self done:nil];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    
    NSString *newstring =  [textField.text stringByReplacingCharactersInRange:range withString:string];
    return newstring.length<16;
    
}
- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event
{
    //    [self.userName resignFirstResponder];
    [self.view endEditing:YES];
}

- (IBAction)cancel:(UIBarButtonItem*)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)done:(UIBarButtonItem*)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [self changeUseName:self.userName.text];
}

- (void)changeUseName:(NSString*)NewName
{
    //去表情
    NewName = [NewName removeEmoji];
    //去两端空格和回车
    NewName = [NewName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//    NSString* url = @"account/userInfo.asp";
//    url = [IPHEAD stringByAppendingString:url];
//    NSDictionary* par = @{ @"nickName" : NewName };
//    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
//    [manager POST:url
//        parameters:par
//        success:^(AFHTTPRequestOperation* _Nonnull operation, id _Nonnull responseObject) {
//            
//            NSLog(@"%@",responseObject);
//            
//            
//            if ([responseObject isKindOfClass:[NSDictionary class]]) {
//                NSString* str = [NSString stringWithFormat:@"%@", [responseObject valueForKeyPath:@"body.result"]];
//                if ([str isEqualToString:@"1"]) {
//                    [[NSUserDefaults standardUserDefaults] setObject:NewName forKey:@"userName"];
//                }
//                else {
//                    
//                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
//                                                                                   message:NSLocalizedString(@"Change the name error", nil)
//                                                                            preferredStyle:UIAlertControllerStyleAlert];
//                    
//                    [self presentViewController:alert animated:YES completion:nil];
//                    
//                    
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        [alert dismissViewControllerAnimated:YES completion:nil];
//                    });
//                }
//            }
//            else {
//                //do something
//            }
//        }
//
//        failure:^(AFHTTPRequestOperation* _Nullable operation, NSError* _Nonnull error) {
//            if (error.code == -1004) {
//                [MBProgressHUD showError:NET_ERROR];
//            }
//            else {
//                [MoreViewController logout:self];
//            }
//        }];
//    
    
    [ChangeUserNameViewModel requestWithUrlForChangeUserName:self andParam:@{@"nickName":NewName} success:^(ChangeUserNameModel *model) {
         [[NSUserDefaults standardUserDefaults] setObject:NewName forKey:@"userName"];
    } failure:^(NSString *error) {
        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:nil];
    }];
}

@end
